<template>
	<view class="container">
		<view class="header">
			<view class="center">
				<view class="store">
					<view class="title">
						<image :src="orderType == 'takein' ? 
							'/static/images/common/star_normal.png' : 
							'/static/images/order/order_icon_address.png'" class="left-icon" />
						<!-- 为了测试方便，这里使用静态店铺数据 -->
						<view class="address">{{ orderType == 'takeout' ? address.AddrComplete_address : shop.name}}
						</view>
						<!-- <image src="/static/images/common/black_arrow_right.png" class="right-icon" @click="showShopPage()" ></image> -->
					</view>
					<!-- 外卖&自取switch begin -->
					<view class="buttons">
						<button type="default" class="button" :class="{active: orderType == 'takein'}" plain
							hover-class="none" @tap="switchOrderType">
							自取
						</button>
						<button type="default" class="button" :class="{active: orderType == 'takeout'}" plain
							hover-class="none" @tap="switchOrderType">
							外卖
						</button>
					</view>
					<!-- 外卖&自取switch end -->
				</view>
				<view class="location">距离您{{shop.distanceL}}m</view>
			</view>
		</view>

		<view v-if="orderType==='takein'" class="bg-white p-30 d-flex align-items-center justify-content-between mb-20">
			<view>
				<text class="mr-20">联系电话</text>
				<text>{{phone}}</text>
			</view>
			<button type="primary" open-type='getPhoneNumber'  @getphonenumber="getPhoneNumber" plain
				class="font-size-sm line-height-1">自动填写</button>
		</view>
		<view v-else>
			<view class="bg-white p-30 d-flex align-items-center justify-content-between">
				<view>
					<text class="mr-20">{{ `联系人：${address.AddrUserName}(${address.AddrGender ? '女士' : '男士'})` }}</text>
					<text>{{`电话： ${address.AddrPhone}`}}</text>
				</view>
			</view>
			<view style="padding-top: 0;" class="bg-white p-30 d-flex align-items-center justify-content-between mb-20">
				{{ `收货地址：${address.Address} ${address.AddrDescription}` }}
			</view>
		</view>


		<view class="bg-white p-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30">取货时间</view>
			<view class="text-color-primary">预约配镜，店铺会致电咨询！</view>
		</view>
		<view class="bg-white pt-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30 pl-30">商品列表</view>
			<list-cell arrow line-right>
				<view class="w-100 d-flex align-items-center overflow-hidden">
					<scroll-view class="flex-fill overflow-hidden" scroll-x>
						<view class="w-100 d-flex align-items-center">
							<image :src="item.image" class="pro-img" v-for="(item, index) in cart" :key="index"></image>
						</view>
					</scroll-view>
					<view class="flex-shrink-0 ml-20">共{{ cartNum }}件</view>
				</view>
			</list-cell>
			<list-cell arrow last>
				<view class="w-100 d-flex align-items-center justify-content-between">
					<view class="d-flex align-items-center">
						<view>优惠券</view>
						<view class="coupon-label">劵</view>
					</view>
					<view class="text-color-assist">暂无可用</view>
				</view>
			</list-cell>
			<list-cell arrow last>
				<view class="w-100 d-flex align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0">备注</view>
					<navigator hover-class="none" class="flex-fill ml-40 text-truncate text-right" open-type="navigate"
						url="/pages/pay/remark">{{ remark }}</navigator>
				</view>
			</list-cell>
			<list-cell last>
				<view class="w-100 d-flex justify-content-end align-items-center">
					<text class="font-size-sm">共{{ cartNum }}件商品，小计</text>
					<text class="font-size-lg font-weight-bold">￥{{ cartAmount }}</text>
				</view>
			</list-cell>
		</view>
		<list-cell last>
			<view class="w-100 d-flex align-items-center justify-content-between">
				<view>支付方式</view>
				<view class="d-flex align-items-center">
					<image src="/static/images/order/weixin-pay.png" class="wx-pay-icon"></image>
					<view>微信</view>
				</view>
			</view>
		</list-cell>
		<view class="footer">
			<view class="mr-30">
				合计：<text class="font-size-lg font-weight-bold">￥{{ cartAmount }}</text>
			</view>
			<button type="primary" @click="saveOrder()">支付</button>
		</view>

		<!-- 登录popup -->
		<login-popup ref="loginPopup"></login-popup>
	</view>
</template>

<script>
	import listCell from '@/components/list-cell/list-cell.vue'
	import loginPopup from '../my/components/login-popup.vue'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		components: {
			listCell,
			loginPopup
		},
		data() {
			return {
				payOptions: {},
				cart: uni.getStorageSync('cart'),
				phone: uni.getStorageSync('userPhone_'+uni.getStorageSync("WxId")),
			}
		},
		computed: {
			...mapState(['address', 'isLogin', 'userInfo', 'shop', 'orderType']),
			cartNum() {
				return this.cart.reduce((acc, cur) => acc + cur.number, 0)
			},
			cartAmount() {
				//return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
				return this.cart.reduce((acc, cur) => acc + cur.number * (cur.price + (cur.selectedMaterials.reduce((ac,
					cr) => ac + cr.price, 0))), 0)
			},
			remark() {
				return this.$store.state.remark
			}
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE']),
			switchOrderType() {
				if (this.orderType === 'takein') {
					uni.navigateTo({
						url: '/pages/addresses/addresses'
					})
				} else {
					this.SET_ORDER_TYPE('takein')
				}
			},
			//this.phone=uni.setStorageSync('userPhone_'+uni.getStorageSync("WxId"), phone);
			getPhoneNumber(e) { //点击获取手机号码按钮
				var that = this;
				wx.checkSession({
					success: function() {
						console.log(e.detail.errMsg)
						console.log(e.detail.iv)
						console.log(e.detail.encryptedData)
						var ency =  encodeURIComponent(e.detail.encryptedData) ;
						var iv =encodeURIComponent(e.detail.iv) ;
						var sessionk =encodeURIComponent( uni.getStorageSync("sessionKey")); // that.data.sessionKey;
						var coid=uni.getStorageSync('coid');
						if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
							that.setData({
								modalstatus: true
							});

						} else { //同意授权
							let Op = {
								url: `api/Sys_User/GetPhoneNumber`,
								data: {
									encryptedData:ency,
									Session_key:sessionk,
									coid:coid,
									IV:iv
								}
							}
							that.$request.Post(Op, (ret) => {
								let res=ret.result;
								if(res.status==true){
									console.log("解密成功~~~~~~~将解密的号码保存到本地~~~~~~~~");
									var phone = res.data;
									that.phone=phone;//WxId
									uni.setStorageSync('userPhone_'+uni.getStorageSync("WxId"), phone);
									console.log(phone);
								}

							});


						}

					},

					fail: function() {
						console.log("session_key 已经失效，需要重新执行登录流程");
						that.wxlogin(); //重新登录
					}
				});
			},

			//保存订单。
			saveOrder() {
				let that = this;
				//是否登入
				if (!this.isLogin) {
					this.$refs['loginPopup'].open();
					return false;
				}
				//判断手机号不能为空
				if (that.phone == "") {
					uni.showModal({
						content: "联系电话不能为空!请点击自动填写！",
						showCancel: false
					});
					return false;
				}

				//物品总价
				let orderTotalMoney = 0;
				//物品规格总价
				let totalMaterialsMoney = 0;

				let detail = [];
				let uid = uni.getStorageSync('WxId');

				this.cart.forEach(c => {
					let currMprice = c.selectedMaterials.reduce((ac, cr) => ac + cr.price, 0);
					let curr = {
						OSProId: c.id,
						OSProImg: c.image,
						OSProName: c.name,
						OSSpec: c.materials_text,
						OSNumber: c.number,
						OSPrice: c.price,
						OSTotalPrice: parseFloat(c.price) * parseFloat(c.number),
						OSRemark: currMprice,
						OSIsDelFlag: 0,
						OSCreateDate: this.$request.getTime(), //new Date(),
						elementIdex: 0
					};

					detail.push(curr);
					//this.cart.reduce((acc, cur) => acc + cur.number * (cur.price+(cur.selectedMaterials.reduce((ac,cr)=>ac + cr.price,0) )), 0);//
					orderTotalMoney += curr.OSTotalPrice;
					totalMaterialsMoney += parseFloat(currMprice) * parseFloat(c.number);
				});

				let coid = uni.getStorageSync('coid');
				let op = {
					url: "api/Lx_Self_Orders/UI_Add",
					data: {
						mainData: {
							OCoId: coid,
							OCode: Date.parse(new Date()),
							OCusId: uid,
							OCusName: that.orderType === 'takein' ? that.phone : this.address.name,
							OCusPhone: that.orderType === 'takein' ? that.phone : this.address.phone,
							OCusAddress: that.orderType === 'takein' ? that.phone : this.address.address,
							OStatus: 0,
							OPayType: 0,
							OSendType: 1,
							OCoupon: 0,
							OIntegral: 0,
							OSendPrice: 0,
							OJGPrice: totalMaterialsMoney,
							OAllPrice: orderTotalMoney,
							OCouponId: 0,
							OoutTradeNo: '',
							ORemark: '',
							OCreateDate: this.$request.getTime(),
							OIsDelFlag: 0

						}, //this.formFileds
						detailData: detail,
						delKeys: null
					}
				}
				this.$request.Post(op, (ret) => {
					if (ret.code == "311") {
						uni.showToast({
							title: ret.message,
							duration: 2000,
							mask: false,
							icon: "none"
						})
						//清空购物车
						let cartKey = "cart" + uid;
						this.$request.setItemLocalstorage(cartKey, "");
						let rslData = JSON.parse(ret.data);

						that.weixinPay(rslData.data.Id);
						//跳转订单
						// uni.switchTab({
						// 	url: `/pages/order/order`
						// });
					}

				});

			},


			//微信小程序内支付
			weixinPay(orderId) {
				console.log("发起支付");
				let that = this;
				this.loading = true;

				uni.login({
					success: (e) => {
						console.log("login success", e); //wxOpenId
						var userOpenid = wx.getStorageSync("wxOpenId");
						console.log(userOpenid);
						//获取支付参数
						let cateOp = {
							url: `api/Sys_User/WxPayH5?orderId=${orderId}&feed=&userId=${wx.getStorageSync("WxId")}&apiType=${userOpenid}`,
							data: ""
						}
						this.$request.Post(cateOp, (res) => {
							that.payOptions = JSON.parse(res.data);
							console.log("pay request success", res);
							console.log("得到接口prepay_id", res.data);
							let paymentData = JSON.parse(res.data);
							uni.requestPayment({
								timeStamp: paymentData.timestamp,
								nonceStr: paymentData.noncestr,
								package: paymentData.package,
								signType: 'MD5',
								paySign: paymentData.sign,
								success: (res) => {
									uni.showToast({
										title: "支付成功!"
									});
									//that.payResultHandler(orderId);
									uni.navigateTo({
										url: `/pages/order/order`
									});
								},
								fail: (res) => {
									uni.showModal({
										content: "支付失败!",
										showCancel: false
									});
									uni.navigateTo({
										url: `/pages/order/order`
									});
								},
								complete: () => {
									this.loading = false;
								}
							})
						});

					},
					fail: (e) => {
						console.log("fail", e);
						this.loading = false;
						uni.showModal({
							content: "支付失败!",
							showCancel: false
						})
					}
				})
			},

			//查询订单是否支付成功 并且完成后续任务。
			payResultHandler(orderId) {
				let feed = this.cartAmount();
				let Op = {
					url: "api/Sys_User/QueryOrderPayResult?outTradeNo=" + this.payOptions.tradeno +
						"&payType=3&feed=" + feed +
						"&userId=" + wx.getStorageSync("WxId") + "&orderId=" + orderId,
					data: ""
				}
				this.$request.Post(Op, (ret) => {
					uni.navigateTo({
						url: `/pages/order/order`
					});
				});
			},
		}

	}
</script>

<style lang="scss" scoped>
	@import '../index/index.scss';

	.container {
		height: auto;
		padding-bottom: 120rpx;
	}

	.pro-img {
		width: 120rpx;
		height: 90rpx;
		flex-shrink: 0;
	}

	.coupon-label {
		background-color: $color-primary;
		color: #FFFFFF;
		font-size: 18rpx;
		line-height: 0.9rem;
		width: 0.9rem;
		height: 0.9rem;
		margin-left: 10rpx;
		text-align: center;
	}

	.wx-pay-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.footer {
		background-color: #FFFFFF;
		z-index: 10;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;

		button {
			width: 250rpx;
			text-align: center;
			padding: 0;
			height: 100%;
			line-height: 100rpx;
			border-radius: 0 !important;
			font-size: $font-size-lg;
		}
	}
</style>
